/**
 * 游戏Agent演示组件
 * 展示基于Mastra AI Agent的新架构使用方式
 */

import React, { useState } from 'react';
import { useGameAgent } from '../../hooks/useGameAgent';
import { GameConfig } from '../../agents/mastra-integration';

/**
 * 游戏Agent演示组件
 */
export const GameAgentDemo: React.FC = () => {
  const {
    gameState,
    isLoading,
    error,
    lastResponse,
    startNewGame,
    chatWithSuspect,
    submitDeduction,
    getGameStatus,
    pauseGame,
    resumeGame,
    endGame,
    clearError,
    resetGame
  } = useGameAgent();

  // 本地状态
  const [gameConfig, setGameConfig] = useState<GameConfig>({
    difficulty: 'normal',
    theme: '办公室',
    suspectCount: 3,
    playerProfile: {
      name: '玩家',
      experience: '新手'
    }
  });

  const [chatInput, setChatInput] = useState('');
  const [selectedSuspect, setSelectedSuspect] = useState('suspect-1');
  const [deductionForm, setDeductionForm] = useState({
    culpritId: '',
    reasoning: '',
    evidence: [] as string[],
    confidence: 50
  });

  // 处理开始新游戏
  const handleStartGame = async () => {
    console.log('🎮 开始新游戏:', gameConfig);
    const response = await startNewGame(gameConfig);
    console.log('游戏开始响应:', response);
  };

  // 处理与嫌疑人对话
  const handleChat = async () => {
    if (!chatInput.trim()) return;
    
    console.log('💬 发送对话:', { selectedSuspect, chatInput });
    const response = await chatWithSuspect(selectedSuspect, chatInput);
    console.log('对话响应:', response);
    setChatInput('');
  };

  // 处理提交推理
  const handleSubmitDeduction = async () => {
    if (!deductionForm.culpritId || !deductionForm.reasoning) {
      alert('请填写完整的推理信息');
      return;
    }

    console.log('🔍 提交推理:', deductionForm);
    const response = await submitDeduction(deductionForm);
    console.log('推理响应:', response);
  };

  // 获取阶段显示文本
  const getPhaseText = (phase: string) => {
    const phaseMap: Record<string, string> = {
      idle: '待机',
      initializing: '初始化中',
      investigation: '调查中',
      deduction: '推理中',
      completed: '已完成',
      paused: '已暂停',
      error: '错误'
    };
    return phaseMap[phase] || phase;
  };

  // 获取状态颜色
  const getPhaseColor = (phase: string) => {
    const colorMap: Record<string, string> = {
      idle: 'text-gray-500',
      initializing: 'text-blue-500',
      investigation: 'text-green-500',
      deduction: 'text-yellow-500',
      completed: 'text-purple-500',
      paused: 'text-orange-500',
      error: 'text-red-500'
    };
    return colorMap[phase] || 'text-gray-500';
  };

  return (
    <div className="max-w-6xl mx-auto p-6 space-y-6">
      {/* 标题 */}
      <div className="text-center">
        <h1 className="text-3xl font-bold text-blue-600 mb-2">
          🎮 赛博侦探游戏 - AI Agent架构演示
        </h1>
        <p className="text-gray-600">
          基于Mastra AI Agent的智能游戏体验
        </p>
      </div>

      {/* 游戏状态面板 */}
      <div className="bg-white rounded-lg shadow-md p-6">
        <h2 className="text-xl font-semibold mb-4">🎯 游戏状态</h2>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="text-center">
            <div className="text-sm text-gray-500">阶段</div>
            <div className={`font-semibold ${getPhaseColor(gameState.phase)}`}>
              {getPhaseText(gameState.phase)}
            </div>
          </div>
          <div className="text-center">
            <div className="text-sm text-gray-500">会话ID</div>
            <div className="font-mono text-xs">
              {gameState.sessionId ? gameState.sessionId.slice(-8) : '无'}
            </div>
          </div>
          <div className="text-center">
            <div className="text-sm text-gray-500">剩余时间</div>
            <div className="font-semibold">
              {gameState.timeRemaining ? `${Math.floor(gameState.timeRemaining / 60)}:${(gameState.timeRemaining % 60).toString().padStart(2, '0')}` : '--:--'}
            </div>
          </div>
          <div className="text-center">
            <div className="text-sm text-gray-500">得分</div>
            <div className="font-semibold text-green-600">
              {gameState.score || 0}
            </div>
          </div>
        </div>
      </div>

      {/* 错误显示 */}
      {error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4">
          <div className="flex justify-between items-center">
            <div className="text-red-800">
              <strong>错误:</strong> {error}
            </div>
            <button
              onClick={clearError}
              className="text-red-600 hover:text-red-800"
            >
              ✕
            </button>
          </div>
        </div>
      )}

      {/* 游戏配置和控制 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 游戏配置 */}
        <div className="bg-white rounded-lg shadow-md p-6">
          <h2 className="text-xl font-semibold mb-4">⚙️ 游戏配置</h2>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                难度
              </label>
              <select
                value={gameConfig.difficulty}
                onChange={(e) => setGameConfig(prev => ({ 
                  ...prev, 
                  difficulty: e.target.value as 'easy' | 'normal' | 'hard' 
                }))}
                className="w-full border border-gray-300 rounded-md px-3 py-2"
                disabled={gameState.phase !== 'idle'}
              >
                <option value="easy">简单</option>
                <option value="normal">普通</option>
                <option value="hard">困难</option>
              </select>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                主题
              </label>
              <input
                type="text"
                value={gameConfig.theme || ''}
                onChange={(e) => setGameConfig(prev => ({ ...prev, theme: e.target.value }))}
                placeholder="例如：办公室、学校、酒店"
                className="w-full border border-gray-300 rounded-md px-3 py-2"
                disabled={gameState.phase !== 'idle'}
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                嫌疑人数量
              </label>
              <input
                type="number"
                min="2"
                max="6"
                value={gameConfig.suspectCount || 3}
                onChange={(e) => setGameConfig(prev => ({ 
                  ...prev, 
                  suspectCount: parseInt(e.target.value) 
                }))}
                className="w-full border border-gray-300 rounded-md px-3 py-2"
                disabled={gameState.phase !== 'idle'}
              />
            </div>
          </div>
        </div>

        {/* 游戏控制 */}
        <div className="bg-white rounded-lg shadow-md p-6">
          <h2 className="text-xl font-semibold mb-4">🎮 游戏控制</h2>
          <div className="space-y-3">
            <button
              onClick={handleStartGame}
              disabled={isLoading || gameState.phase === 'investigation'}
              className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
            >
              {isLoading ? '🔄 处理中...' : '🚀 开始新游戏'}
            </button>
            
            <div className="grid grid-cols-2 gap-2">
              <button
                onClick={pauseGame}
                disabled={isLoading || gameState.phase !== 'investigation'}
                className="bg-orange-600 text-white py-2 px-4 rounded-md hover:bg-orange-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
              >
                ⏸️ 暂停
              </button>
              
              <button
                onClick={resumeGame}
                disabled={isLoading || gameState.phase !== 'paused'}
                className="bg-green-600 text-white py-2 px-4 rounded-md hover:bg-green-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
              >
                ▶️ 恢复
              </button>
            </div>
            
            <div className="grid grid-cols-2 gap-2">
              <button
                onClick={getGameStatus}
                disabled={isLoading || !gameState.sessionId}
                className="bg-purple-600 text-white py-2 px-4 rounded-md hover:bg-purple-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
              >
                📊 获取状态
              </button>
              
              <button
                onClick={resetGame}
                disabled={isLoading}
                className="bg-red-600 text-white py-2 px-4 rounded-md hover:bg-red-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
              >
                🔄 重置游戏
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 对话界面 */}
      {gameState.phase === 'investigation' && (
        <div className="bg-white rounded-lg shadow-md p-6">
          <h2 className="text-xl font-semibold mb-4">💬 嫌疑人对话</h2>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                选择嫌疑人
              </label>
              <select
                value={selectedSuspect}
                onChange={(e) => setSelectedSuspect(e.target.value)}
                className="w-full border border-gray-300 rounded-md px-3 py-2"
              >
                {Array.from({ length: gameState.suspectCount || 3 }, (_, i) => (
                  <option key={i} value={`suspect-${i + 1}`}>
                    嫌疑人 {i + 1}
                  </option>
                ))}
              </select>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                你的问题
              </label>
              <div className="flex space-x-2">
                <input
                  type="text"
                  value={chatInput}
                  onChange={(e) => setChatInput(e.target.value)}
                  placeholder="输入你想问的问题..."
                  className="flex-1 border border-gray-300 rounded-md px-3 py-2"
                  onKeyPress={(e) => e.key === 'Enter' && handleChat()}
                />
                <button
                  onClick={handleChat}
                  disabled={isLoading || !chatInput.trim()}
                  className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 disabled:bg-gray-400"
                >
                  发送
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 推理提交 */}
      {gameState.phase === 'investigation' && (
        <div className="bg-white rounded-lg shadow-md p-6">
          <h2 className="text-xl font-semibold mb-4">🔍 提交推理</h2>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                真凶
              </label>
              <select
                value={deductionForm.culpritId}
                onChange={(e) => setDeductionForm(prev => ({ ...prev, culpritId: e.target.value }))}
                className="w-full border border-gray-300 rounded-md px-3 py-2"
              >
                <option value="">请选择真凶</option>
                {Array.from({ length: gameState.suspectCount || 3 }, (_, i) => (
                  <option key={i} value={`suspect-${i + 1}`}>
                    嫌疑人 {i + 1}
                  </option>
                ))}
              </select>
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                推理过程
              </label>
              <textarea
                value={deductionForm.reasoning}
                onChange={(e) => setDeductionForm(prev => ({ ...prev, reasoning: e.target.value }))}
                placeholder="详细说明你的推理过程..."
                rows={4}
                className="w-full border border-gray-300 rounded-md px-3 py-2"
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                信心程度: {deductionForm.confidence}%
              </label>
              <input
                type="range"
                min="0"
                max="100"
                value={deductionForm.confidence}
                onChange={(e) => setDeductionForm(prev => ({ ...prev, confidence: parseInt(e.target.value) }))}
                className="w-full"
              />
            </div>
            
            <button
              onClick={handleSubmitDeduction}
              disabled={isLoading || !deductionForm.culpritId || !deductionForm.reasoning}
              className="w-full bg-green-600 text-white py-2 px-4 rounded-md hover:bg-green-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
            >
              🎯 提交推理
            </button>
          </div>
        </div>
      )}

      {/* 最后响应显示 */}
      {lastResponse && (
        <div className="bg-gray-50 rounded-lg p-6">
          <h2 className="text-xl font-semibold mb-4">📋 最后响应</h2>
          <div className="bg-white rounded border p-4">
            <div className="mb-2">
              <span className={`inline-block px-2 py-1 rounded text-sm ${
                lastResponse.success ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
              }`}>
                {lastResponse.success ? '✅ 成功' : '❌ 失败'}
              </span>
            </div>
            <div className="text-sm text-gray-600 mb-2">
              <strong>消息:</strong> {lastResponse.message}
            </div>
            {lastResponse.agentResponse && (
              <div className="text-sm text-gray-600">
                <strong>Agent响应:</strong> {lastResponse.agentResponse}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};
